import { getInfo, login, logout } from '@/api/user'
import { getToken, removeToken } from '@/utils/auth'
import defaultSettings from '@/settings'
const { defaultAvatar } = defaultSettings

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    depName: '',
    code: '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_USER_INFO: (state, val) => {
    Object.assign(state.userInfo, val)
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_DEP_NAME: (state, depname) => {
    state.depName = depname || '暂无'
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar || defaultAvatar
  },
  SET_CODE: (state, code) => {
    state.code = code
  }
}
const actions = {
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  },
  login({ commit }, loginForm) {
    const { userName, password } = loginForm
    return new Promise((resolve, reject) => {
      login({ userName, password })
        .then(res => {
          commit('SET_TOKEN', res.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          const { data } = response
          if (!data) {
            return reject('Verification failed, please Login again.')
          }
          const { xm, avatar } = data
          commit('SET_NAME', xm)
          commit('SET_USER_INFO', data)
          commit('SET_AVATAR', avatar)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
